package com.csun.cmny.provider.device.patrol;

import com.csun.cmny.provider.device.patrol.entity.PatrolCmdEntity;

import java.time.LocalDateTime;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2021/7/28 18:14
 * @Description: 巡更棒消息编码器
 */
public class PatrolMessageEncoder {

    /**
     * 服务器向设备返回数据格式
     * --------------------------------------------------------------
     *   0xbb 0xbb  |  0xb1  |  LEN  |  数据  |  XOR  |  0x0d 0x0a
     * --------------------------------------------------------------
     *     数据头   |  命令   | 长度  |  1位  |  校验  |     结尾
     * --------------------------------------------------------------
     * LEN 为 2
     * 数据: Y 或 N Y 表示接收数据正确 N 表示失败
     * XOR：前所有字节异或再加１
     *
     * @param patrolCmdEntity
     * @param status
     * @return
     */
    public static byte[] buildCardReadAckMsg(PatrolCmdEntity patrolCmdEntity, byte status) {

        byte[] msg = new byte[8];

        msg[0] = patrolCmdEntity.head[0];
        msg[1] = patrolCmdEntity.head[1];
        msg[2] = (byte) 0xb1;
        msg[3] = 2;
        msg[4] = status;
        msg[5] = (byte) ((msg[2] ^ msg[3] ^ msg[4]) + 1);
        msg[6] = 0x0d;
        msg[7] = 0x0a;

        return msg;
    }

    /**
     * 服务器向设备回复查询命令
     *
     * @return
     */
    public static byte[] buildCmdAckMsg() {
        return new byte[] {(byte) 0xbb, (byte) 0xbb, (byte) 0xd0,
                0x02, 0x00, (byte) 0xd3, 0x0d, 0x0a};
    }

    /**
     * 发送时间
     *
     * @return
     */
    public static byte[] buildTimeAckMsg() {

        LocalDateTime now = LocalDateTime.now();
        int nsec = now.getSecond();
        nsec = 16 * (nsec / 10) + nsec % 10;
        int nmin = now.getMinute();
        nmin = 16 * (nmin / 10) + nmin % 10;
        int nhou = now.getHour();
        nhou = 16 * (nhou / 10) + nhou % 10;
        int nday = now.getDayOfMonth();
        nday = 16 * (nday / 10) + nday % 10;
        int nmon = now.getMonthValue();
        nmon = 16 * (nmon / 10) + nmon % 10;
        int nyear = now.getYear() % 100;
        nyear = 16 * (nyear / 10) + nyear % 10;
        int week = now.getDayOfWeek().getValue();
        if (week == 7) {
            week = 0;
        }
        int nc1 = (0xbb ^ 0xbb ^ 0xb2 ^ 0x08 ^ nyear ^ nmon ^ nday ^ nhou ^ nmin ^ nsec ^ week) + 1;
        nc1 = nc1 % 256;
        return new byte[] {
                (byte) 0xbb, (byte) 0xbb, (byte) 0xb2, 0x08,
                (byte) nyear, (byte) nmon, (byte) nday, (byte) nhou, (byte) nmin, (byte) nsec, (byte) week,
                (byte) nc1,
                0x0d, 0x0a
        };
    }

}
